package fi.profecons.csswindows.toolkit;

import java.awt.Color;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import fi.profecons.csswindows.Element;
import fi.profecons.csswindows.RestrictedContainer;

public class Table extends RestrictedContainer {

	private Vector altColor = new Vector();

	private int numberOfColumns = 0;

	private int cellCount = 0;

	public Table() {
		super();
		addCommand("new Table('" + getId() + "');");
	}

	public Table(int rows, int cells) {
		super();
		addCommand("new Table('" + getId() + "');");
		for (int i = 0; i < rows; i++) {
			addRow(cells);
		}
	}

	public Vector getRows() {
		return getAll();
	}

	public void addRow(TableRow row) {
		this.add(row);
		addCommand("getElement('" + getId() + "').addElement(getElement('"
				+ row.getId() + "'));");
		if (this.altColor.size() > 0) {
			int color = getAll().size() % this.altColor.size();
			row.setBgColor((Color) altColor.get(color));
		}
	}

	public void addCell(TableCell cell) {
		if (cellCount == 0) {
			addRow();
		} else if (numberOfColumns > 0) {
			if (cellCount % numberOfColumns == 0) {
				addRow();
			}
		}
		TableRow currentRow = (TableRow) getAll().lastElement();
		if (currentRow != null) {
			currentRow.addCell(cell);
		}
		cellCount++;

	}

	public void addCell(Element element) {
		TableCell cell = new TableCell();
		cell.add(element);
		addCell(cell);
	}

	public TableRow addRow(int cells) {
		TableRow row = new TableRow(cells);
		addRow(row);
		return row;
	}

	public TableRow getRow(int rowNum) {
		return (TableRow) getAll().get(rowNum);
	}

	public TableRow addRow() {
		return addRow(0);
	}

	public int numberOfRows() {
		return getAll().size();
	}

	public Vector getAltColor() {
		return altColor;
	}

	public void setAltColor(Vector altColor) {
		this.altColor = altColor;
		if (this.altColor.size() > 0) {
			for (int i = 0; i < getAll().size(); i++) {
				TableRow row = getRow(i);
				int color = i % this.altColor.size();
				row.setBgColor((Color) altColor.get(color));
			}
		}
	}

	public int getNumberOfColumns() {
		return numberOfColumns;
	}

	public void setNumberOfColumns(int numberOfColumns) {
		this.numberOfColumns = numberOfColumns;
	}

	public int getWidth() {
		int width = 0;
		Iterator i = getAll().iterator();
		while (i.hasNext()) {
			TableRow row = (TableRow) i.next();
			if (row.getWidth() > width)
				width = row.getWidth();
		}
		return width;
	}

	public int getHeight() {
		int height = 0;
		Iterator i = getAll().iterator();
		while (i.hasNext()) {
			TableRow row = (TableRow) i.next();
			height += row.getHeight();
		}
		return height;
	}
}
